package io.renren.modules.api.controller;


import com.google.code.kaptcha.Producer;
import io.renren.common.utils.ConstantUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.common.validator.Assert;
import io.renren.modules.api.annotation.AuthIgnore;
import io.renren.modules.api.service.UsertokenService;
import io.renren.modules.user.service.UserinfosService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * API登录授权
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {
    @Autowired
    private UserinfosService userService;
    @Autowired
    private UsertokenService tokenService;
    @Autowired
    private Producer producer;

    /**
     * 登录
     */
    @AuthIgnore
    @PostMapping("login")
    public R login(String useraccount, String userpwd, String captcha){
        Assert.isBlank(useraccount, "您的用户账户不能为空");
        Assert.isBlank(userpwd, "您的密码不能为空");
        Assert.isBlank(captcha, "您的验证码不能为空");

        String kaptcha = ShiroUtils.getKaptcha(ConstantUtils.LOGIN_KAPTCHA_SESSION_KEY);
        if(!captcha.equalsIgnoreCase(kaptcha)){
            return R.error("您的验证码不正确");
        }
        //用户登录
        String userId = userService.login(useraccount, userpwd);

        //生成token
        Map<String, Object> map = tokenService.createToken(userId);

        return R.ok(map);
    }
    @AuthIgnore
    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);

        //保存到shiro session
        ShiroUtils.setSessionAttribute(ConstantUtils.LOGIN_KAPTCHA_SESSION_KEY, text);
        //返回图片
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

}
